<?php
namespace app\admin\logic;

use app\common\logic\Base;
use think\facade\App;

class Config extends Base {

    /**
     * @desc 管理管理
     * @param array $params
     * @return array
     */
    public function index($params) {
        $where = [];
        if($params['keyword']) {
            $where[] = ['sc_title', 'like', '%' .$params['keyword']. '%'];
        }

        if($params['group']) {
            $where[] = ['sc_group', '=', $params['group']];
        }

        $list = App::model('SiteConfig')->where($where)->select();
        return [
            'list' => output_format($list, 'sc')
        ];
    }

    /**
     * @desc 编辑配置
     * @param $params
     * @return array
     */
    public function edit($params) {
        $list = App::model('SiteConfig')
            ->where(['sc_id' => $params['id']])
            ->find();

        return [
            'info' => output_format($list, 'sc')
        ];
    }

    /**
     * @desc 栏目分类 (添加、编辑)
     * @param array $params
     * @return array|bool
     */
    public function operateAjax($params) {
        $data = [
            'sc_title' => $params['title'],
            'sc_key'   => $params['key'],
            'sc_value' => $params['value'],
            'sc_group' => $params['group']
        ];

        $data = array_filter($data, function($arr) {
            if($arr === '' || $arr === null) {
                return false;
            }
            return true;
        });

        if($params['action'] == 'add') {
            $info = App::model('SiteConfig')->where('sc_key', '=', $params['key'])->find();
            if($info) {
                $this->errorCode = EC_AD_CONFIG_KEY_ALREADY_EXIST;
                return false;
            }

            $result = App::model('SiteConfig')->insertGetId($data);
        }else {
            $result = App::model('SiteConfig')
                ->where(['sc_id' => $params['id']])
                ->update($data);
        }
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }
}